package com.hermit.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hermit.server.domain.*;
import com.hermit.server.dto.*;
import com.hermit.server.enums.CourseStatusEnum;
import com.hermit.server.mapper.*;
import com.hermit.server.mapper.yfmap.MyCourseMapper;
import com.hermit.server.util.CopyUtil;
import com.hermit.server.util.UUidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.support.SessionFlashMapManager;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;


@Service
public class CourseService {
    @Resource
    private CourseMapper courseMapper;

    @Resource
    private MyCourseMapper myCourseMapper;

    @Resource
    private CourseCategoryService courseCategoryService;

    @Resource
    private CourseContentMapper courseContentMapper;

    @Resource
    private TeacherService teacherService;

    @Resource
    private ChapterService chapterService;

    @Resource
    private SectionService sectionService;

    /**
     * 查询
     */
    public void list(CoursePageDto pageDto) {
//        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
//        CourseExample courseExample = new CourseExample();
//
//        CourseExample.Criteria criteria = courseExample.createCriteria();
//        if(!StringUtils.isEmpty(pageDto.getStatus())){
//            criteria.andStatusEqualTo(pageDto.getStatus());
//        }
//
//
//        /** 根据sort来排序*/
//        courseExample.setOrderByClause("sort asc");
//
//        List<Course> courseList = courseMapper.selectByExample(courseExample);
//        //查询数据
//        PageInfo<Course> pageInfo = new PageInfo<>(courseList);
//        //设置已查询条数
//        pageDto.setTotal(pageInfo.getTotal());
//
//        List<CourseDto> courseDtoList = CopyUtil.copyList(courseList,CourseDto.class);
//        //设置最终查询结果
//        pageDto.setList(courseDtoList);
//        //return pageDto;  pageDto是从前端传递来的，按道理应该有返回值，此处传入对象==返回对象，属于原地返回（杨凡专用名词）
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        List<CourseDto> courseDtoList = myCourseMapper.list(pageDto);
        PageInfo<CourseDto> pageInfo = new PageInfo<>(courseDtoList);
        pageDto.setTotal(pageInfo.getTotal());
        pageDto.setList(courseDtoList);
    }
    /** 保存*/
    @Transactional
    public void save(CourseDto courseDto) {
        Course course = CopyUtil.copy(courseDto, Course.class);
        if (StringUtils.isEmpty(courseDto.getId())) {
            this.insert(course);
        } else {
            this.update(course);
        }

        /**批量保存分类*/
        courseCategoryService.saveBatch(course.getId(), courseDto.getCategorys());
    }
    /**新增 */
    private void insert(Course course){
        Date now = new Date();
        course.setCreatedAt(now);
        course.setUpdatedAt(now);
        course.setId(UUidUtil.getShortUuid());
        courseMapper.insert(course);
    }
    /**修改更新 */
    private void update(Course course){
        course.setUpdatedAt(new Date());
        courseMapper.updateByPrimaryKey(course);
    }

    /**
     * 删除
     */
    public void delete(String id) {
        courseMapper.deleteByPrimaryKey(id);
    }

    /**
     * 封装自定义更新视频时长接口
     */
    public void updateTime(String courseId) {
        myCourseMapper.updateTime(courseId);
    }

    /**
     * 查找课程类容
     */
    public CourseContentDto findContent(String id) {
        CourseContent content = courseContentMapper.selectByPrimaryKey(id);
        if (content == null) {
            return null;
        }
        return CopyUtil.copy(content, CourseContentDto.class);
    }

    /**
     * 保存/修改课程类容
     */
    public int saveContent(CourseContentDto contentDto) {
        CourseContent content = CopyUtil.copy(contentDto, CourseContent.class);
        int j = courseContentMapper.updateByPrimaryKeyWithBLOBs(content);
        if (j == 0) {
            j = courseContentMapper.insert(content);
        }
        return j;
    }

    /**
     * 更新排序
     */
    public void sort(SortDto sortDto) {
        //修改当前数据
        myCourseMapper.updateSort(sortDto);
        //变大
        if (sortDto.getNewSort() > sortDto.getOldSort()) {
            myCourseMapper.moveSortsForward(sortDto);
        }
        //变小
        if (sortDto.getNewSort() < sortDto.getOldSort()) {
            myCourseMapper.moveSortsBackword(sortDto);
        }
    }

    /**
     * 新课列表查询，按日期查询已发布课程
     */
    public List<CourseDto> listNew(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        CourseExample example = new CourseExample();
        example.createCriteria().andStatusEqualTo(CourseStatusEnum.PUBLISH.getCode());
        example.setOrderByClause("created_at desc");
        List<Course> courseList = courseMapper.selectByExample(example);
        return CopyUtil.copyList(courseList,CourseDto.class);
    }

    /**
     * 热门课程列表查询，按日期查询已发布课程
     */
    public List<CourseDto> listHot(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        CourseExample example = new CourseExample();
        example.createCriteria().andStatusEqualTo(CourseStatusEnum.PUBLISH.getCode());
        example.setOrderByClause("enroll desc");
        List<Course> courseList = courseMapper.selectByExample(example);
        return CopyUtil.copyList(courseList,CourseDto.class);
    }

    /**
     * web页面根据id查询courseDto所有信息 （包括课程信息，教师，小节，大章，描述）
     */
    public CourseDto findCourse(String id){
        //1.先查course基本信息
        Course course = courseMapper.selectByPrimaryKey(id);
        if(course == null || !CourseStatusEnum.PUBLISH.getCode().equals(course.getStatus())){
            return null;
        }
        CourseDto courseDto = CopyUtil.copy(course ,CourseDto.class);
        //2.查内容
        CourseContent content = courseContentMapper.selectByPrimaryKey(id);
        if(content != null){
            courseDto.setContent(content.getContent());
        }
        //3.查讲师信息
        TeacherDto teacherDto = teacherService.findById(courseDto.getTeacherId());
        courseDto.setTeacher(teacherDto);

        //4.查大章信息
        List<ChapterDto> chapterDtoList = chapterService.listByCourse(id);
        courseDto.setChapters(chapterDtoList);

        //5.查小节信息
        List<SectionDto> sectionDtoList = sectionService.listByCourse(id);
        courseDto.setSections(sectionDtoList);

        return courseDto;


    }
}